package feedme.dao.impl;

import java.net.UnknownHostException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;
import org.bson.NewBSONDecoder;
import org.bson.types.ObjectId;
import org.omg.CORBA.IdentifierHelper;

import utils.io.StreamUtil;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

import feedme.bean.FoodServerBean;
import feedme.dao.FoodServerDao;

@SuppressWarnings("unused")
public class MongoDBFoodServerDaoImpl 
    extends MongoDBBaseDaoImpl 
    implements FoodServerDao {
    
    static private final Logger logger = Logger.getLogger(MongoDBFoodServerDaoImpl.class);
   
    
    MongoDBFoodServerDaoImpl() throws UnknownHostException{
      //  db = dbDriver.getDB(getDbName()); 
      //  collection = db.getCollection("FoodServer");
    }
  

    public List<?> findAll() throws UnknownHostException {

        
        logger.info("FoodServer collection.size:" + getDBCollection().getCount());
        @SuppressWarnings("unchecked")
        //List<DBObject> resTmp = collection.distinct("");
        List<FoodServerBean> res = new LinkedList<FoodServerBean>();
        
        DBCursor cur = getDBCollection().find();;
        while (cur.hasNext()) {
            DBObject object = cur.next();
            res.add(DBObject2Bean(object));
        }
        
      
       
        return res;
    }

    @Override
    public boolean save(Object obj) throws Exception {
        return save((FoodServerBean)obj);
    }
    
    public boolean save(FoodServerBean fsBean) throws Exception {
        try {
            
            /**
             * save操作如果没有id，需要给予id
             */
            
            //if (fsBean.getId() == 0) {
                /**
                 * 系统给予自增id
                 */
             //   fsBean.setId(createIncreasedId());
            //}
       
            
            DBObject fs = Bean2BaseDBObject(fsBean);
            logger.info(getDBCollection().save(fs).getN());
        } catch (Exception e) {
            e.printStackTrace();
            return true;
        }
        return false;
    }
    
    @Deprecated
    private int createIncreasedId(){
        DBCursor cursor;
        try {
            cursor = getDBCollection()
                    .find().sort(new BasicDBObject("$natural",-1)).limit(1);
            if(cursor.hasNext()){  
                return Integer.parseInt(cursor.next().get("_id").toString())+1;  
            }else{  
                return 0;  
            }  
        } catch (UnknownHostException e) {
            e.printStackTrace();
            return 0;
        } 
   
    }
    
   
    
    private DBObject Bean2BaseDBObject(FoodServerBean fsBean){
        DBObject fs = new BasicDBObject();
        if (fsBean.getObjId().isEmpty() == false) {
            fs.put("_id", new ObjectId(fsBean.getObjId()));
        }
      ///  fs.put("id", fsBean.getId());
        fs.put("name",fsBean.getName());
        fs.put("tel",fsBean.getTel());
        return fs;
    }
    
    private FoodServerBean DBObject2Bean(DBObject dbObj){
        FoodServerBean fsBean = new FoodServerBean();
        
        fsBean.setObjId(dbObj.get("_id").toString());
       // fsBean.setId((Integer)dbObj.get("id"));
        fsBean.setName((String)dbObj.get("name"));
        fsBean.setTel((String)dbObj.get("tel"));
        
        return fsBean;
    }






    @Override
    public boolean delete(Object obj) throws Exception {
        return delete((FoodServerBean)obj);
    }
    
    public boolean delete(FoodServerBean fsBean) throws Exception {
        try {
            BasicDBObject query = new BasicDBObject();
            query.put(
                "_id", 
                new ObjectId(fsBean.getObjId())
                );
            //query.put("id", fsBean.getId());
            
            
            
            DBCursor cur = getDBCollection().find(query);
            while(cur.hasNext()) {
                DBObject obj = cur.next();
                logger.debug("delete find:" + obj);
                logger.info(getDBCollection().remove(obj).getN());
            }
            
            DBObject fs = Bean2BaseDBObject(fsBean);
            
        } catch (Exception e) {
            e.printStackTrace();
            return true;
        }
        return false;
    }
}
